package com.yunc.common.web.interceptor;

import com.yunc.common.core.constant.AuthConstants;
import com.yunc.common.web.aspect.AuthIgnore;
import com.yunc.common.web.exception.SecurityException;
import com.yunc.common.web.util.JwtTokenUtils;
import com.yunc.common.web.util.UserContext;
import com.yunc.common.web.util.WebUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * response.getWriter().write(JSONUtil.toJsonStr(R.error(HttpServletResponse.SC_FORBIDDEN, "Token format error")));
 *
 * @author taocongcong
 * @create 2021-05-19 9:58
 */
@Slf4j
@Component
public class AuthIgnoreInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 验证有无注解
        AuthIgnore authIgnore;
        if (handler instanceof HandlerMethod) {
            authIgnore = ((HandlerMethod)handler).getMethodAnnotation(AuthIgnore.class);
        } else {
            return true;
        }
        if (authIgnore != null){
            return true;
        }
        // 业务处理,从header中获取token
        String token = WebUtils.getRequestParameter(AuthConstants.TOKEN);
        if (StringUtils.isBlank(token)){
            throw new SecurityException("Token不能为空");
        }
        // token不能为空
        boolean flag;
        try {
            flag = JwtTokenUtils.isExpiration(token);
        } catch (Exception e) {
            throw new SecurityException("Token不合法");
        }
        if (flag) {
            throw new SecurityException("Token不合法");
        }
        // 保存到当前线程，那么就直接能获取到值
        Claims claims = JwtTokenUtils.getTokenBody(token);
        UserContext.setUserId((String) claims.get(UserContext.CONTEXT_KEY_USER_ID));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.remove();
    }

}
